package com.boot.webflux.security.example2.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RespUtil {
    public static Mono<Void> writeMsg(ServerHttpResponse response, int status, String msg){
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setRawStatusCode(status);
        DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));

    }

    public static Mono<Void> writeMsg(ServerHttpResponse response,int status, Map<String,Object> map){
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setRawStatusCode(status);
        String body = JSONObject.toJSONString(map);
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));

    }

}
